import os

import requests

from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

from api_server.utils import *
from api_test.common.api_response import JsonResponse


class TankHeroProtocol(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):
        """
        xml格式的http/https协议请求
        """
        xmlfile_path = os.path.dirname(os.path.abspath(__file__)) + "/message.xml"
        # {"url":"http://10.0.101.183:10010/online", "body":{"messagedId":1100,"userName":"TankHero1","version":"","platformId":""}}
        data = JSONParser().parse(request)
        url = data['url']
        raw_data = data["body"]
        try:
            xml_object = ParserXml()
            xml_object.xmlParser(xmlfile_path)

            # print(xml_map)
            #
            send_bytes = xml_object.xml2serial(raw_data)
            # TODO 写死post方法
            result = requests.post(url, data=send_bytes)
            content = result.content

            response_dict = {}
            respId = struct.unpack('>h', content[0:2])[0]
            response_dict["messageId"] = respId

            # param_len = struct.unpack('>h', content[2:4])

            xml_object.content = content[4:]
            xml_object.serial2dict(respId, response_dict)

            return JsonResponse(code="999999", msg="成功", data=response_dict)
        except Exception as e:
            return JsonResponse(code="999999", msg="失败", data=str(e))
